package cn.rtplay.esp32camcar;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.MaterialDialog;

import java.util.Objects;

import cn.rtplay.esp32camcar.databinding.FragmentSteeringDiagramBinding;
import cn.rtplay.esp32camcar.toolUtils.LogUtil;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class SteeringDiagramFragment extends Fragment {
    private final String TAG = "SteeringDiagramFragment";
    private FragmentSteeringDiagramBinding mViewBinding;
    private int lastDegrees;
    private ESP32UDPService mESP32UDPService;
    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mESP32UDPService = ((ESP32UDPService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mESP32UDPService = null;
        }
    };
    private SensorManager sensorMgr;
    SensorEventListener lsn = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (mESP32UDPService != null) {
                if ((mESP32UDPService.getStart()) && (mESP32UDPService.getChargingState() == ESP32UDPService.CHARGING_STATUS_NOT_CHARGING)) {
                    int degrees = (int) Math.toDegrees(Math.atan(event.values[1] / event.values[0]));
                    LogUtil.d(TAG, "onSensorChanged:" + degrees);
                    if ((degrees >= -80) && (degrees <= 80)) {
                        if (lastDegrees != degrees) {
                            mViewBinding.turnView.setRotation(degrees >> 1);
                            mESP32UDPService.setDirectionAngle(degrees >> 1);
                            lastDegrees = degrees;
                        }
                    }
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    public SteeringDiagramFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LogUtil.v(TAG, "onCreateView");
        // Inflate the layout for this fragment
        mViewBinding = FragmentSteeringDiagramBinding.inflate(inflater, container, false);
        if (getActivity() != null) {
            Intent esp32ServiceIntent = new Intent(getActivity(), ESP32UDPService.class);
            getActivity().bindService(esp32ServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
            LogUtil.v(TAG, "onCreateView:sensorMgr");
            sensorMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            if (sensorMgr != null) {
                LogUtil.v(TAG, "onCreateView:sensor");
                Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_GRAVITY);
                if (sensor == null) {
                    LogUtil.e(TAG, "TYPE_GRAVITY is null");
                    sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                }
                if (sensor == null) {
                    LogUtil.e(TAG, "TYPE_ACCELEROMETER is null");
                    new MaterialDialog.Builder(getActivity())
                            .title(getResources().getString(R.string.prompt))
                            .content(getResources().getString(R.string.not_support_gravity))
                            .icon(Objects.requireNonNull(ContextCompat.getDrawable(getActivity(), R.mipmap.ic_launcher)))
                            .canceledOnTouchOutside(false)
                            .positiveText(getResources().getString(R.string.fix))
                            .show();
                }
                sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);
            }
        }
        return mViewBinding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        sensorMgr.unregisterListener(lsn);
        super.onPause();
    }
}